// pages/userLogic/chooseLock/chooseLock.js

//TODO : 正反逻辑
import * as echarts from '../../../ec-canvas/echarts';

import {
  request
} from '../../../common/wx-promise-request.js';
// var util = require('../../../common/wx-promise-request.js');
function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    title: {
      text: '智能逻辑图'
    },
    tooltip: {},
    animationDurationUpdate: 1500,
    animationEasingUpdate: 'quinticInOut',
    series: [{
      type: 'graph',
      layout: 'none',
      symbolSize: 50,
      roam: true,   
      edgeSymbol:["circle","arrow"],
      
      edgeSymbolSize:10,

      label: {
        normal: {
          show: true
        }
      },
      // edgeSymbol: ['circle', 'arrow'],
      // edgeSymbolSize: [4, 10],
      edgeLabel: {
        normal: {
          textStyle: {
            fontSize: 20
          }
        }
      },
      data: [],
      // links: [],
      // {
      //   source: 0,
      //   target: 1,
      //   symbolSize: [5, 20],
      //   label: {
      //     normal: {
      //       show: true
      //     }
      //   },
      //   lineStyle: {
      //     normal: {
      //       width: 4,
      //       curveness: 0.2
      //     }
      //   }
      // }, {
      //   source: '节点2',
      //   target: '节点1',
      //   label: {
      //     normal: {
      //       show: true
      //     }
      //   },
      //   lineStyle: {
      //     normal: {
      //       curveness: 0.2
      //     }
      //   }
      // }, {
      //   source: '节点1',
      //   target: '节点3'
      // }, {
      //   source: '节点2',
      //   target: '节点3'
      // }, {
      //   source: '节点2',
      //   target: '节点4'
      // }, {
      //   source: '节点1',
      //   target: '节点4'
      // }
      links: [],
      // lineStyle: {
      //   normal: {
      //     opacity: 0.9,
      //     width: 2,
      //     curveness: 0
      //   }
      // }
    }]
  };

  chart.setOption(option);
  return chart;
};

function httpPost(url, data) {
  var requestObj = request({
    url: url,
    data: data,
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'chartset': 'utf-8'
    },
  });
  return requestObj
}
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userID: "",
    lock_list: [],
    logicTypeIDModules:{},

    ec: {
      onInit: initChart
    },
    // 智能逻辑所需变量
    sourceModule:{},
    desModule:{},
    hover:false,
    logicModal:false,
    logicLink:{},
    logicToDelete:{},
    configModal:false,
    currentType:null,
    currentID:null,
    logicPolar:1,
    //
    imgShow:null,
    imgUrl:"",
    // 摄像头
    polarLogic:true,
    OfflineModules: [],
   OfflineControlers: [],
    OnlineControlers: [],
    OnlineModule:{},
    AllOffLine: false,
    devices: {},
    echartsData:[],
    moduleDict: {
      0xF: '协调器',
      0x0: '锁体',
      0x1: '扫码模块',
      0x2: 'NFC',
      0x6:'红外传感',
      0x7:'',
      0x5:'气体传感器',
      0x3:'摄像头模块'
    },
    loadModal: false,
    logicDeleteModal:false,
    locknum: 0,
    lock_state: [
      "保持原有状态",
      "开启",
      "关闭",
      "关闭并报警"
    ],
    scanResult: {},
    scanModal: false,
    ModalName: ''
      //这个用于存放提取人脸特征的照片
      ,
    facephoto: [
      "",
      "",
      ""

    ],




    image0: 0,
    image1: 0,
    image2: 0,


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var userID = wx.getStorageSync('userID').userID
    console.log("userID",userID)
    this.setData({
      userID: userID
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
      
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this
    // this.setData({ec:{onInit:initChart}})
    while(that.data.userID==undefined)
    ;
    that.refreshDevices()
    /*************************************
     * 这里将所有的block_state[x].monitor置空
     * 以防止打开界面的时候仍然出现上一次拍摄的照片
     */


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  unfold(e) {
    const that = this
    // console.log(e)
    console.log(that.data.OnlineModules)
    var devices = that.data.devices;
    var index = e.currentTarget.dataset.index;
    devices.olDevices[index].clicked=!devices.olDevices[index].clicked;
    that.setData({
      devices: devices
    });

  },
  addModule(mod) {
    const that = this;
    if (mod != null) {
      httpPost('https://fdxt.xyz:5050', {
        port: JSON.stringify("add_module"),
        userID: JSON.stringify(that.data.userID),
        moduleID:JSON.stringify( mod.ModuleID),
        moduleName: JSON.stringify(mod.ModuleName),
        moduleType: JSON.stringify(mod.ModuleType)
        //自动获取用户信息嵌套进了自动登录中，以解决js执行顺序不是从上到下的问题
      }, ).then((res) => {
        console.log("发送数据为:", mod)
        console.log("收到数据为:", res)
        if(res.data.state=="2")
        {
          wx.showModal({
            title:"设备重复添加，请重试！"
          })
        }
      }).catch((res) => {
        console.log("**********",res)
      })
    }
    setTimeout(that.refreshDevices,100);
  },
  scan() {
    const that = this
    wx.scanCode({
      success(res) {

        var data = JSON.parse(res.result)
        console.log(data)
        try {
          if (data.isModule == 1) {
            that.setData({
              scanResult: {
                'ModuleType': data.ModuleType,
                "ModuleID": data.ModuleID
              },
              scanModal: true
            })
          }
        } finally {
          console.log(data)
        }
      }
    })
  },

  submodule(e) {
    const that = this
    console.log(that.data.ModalName)
    const ModuleForm = {
      ModuleID: that.data.scanResult.ModuleID,
      ModuleName: that.data.ModalName,
      ModuleType: that.data.scanResult.ModuleType
    }
    that.addModule(ModuleForm)
    that.setData({
      scanResult: {},
      ModuleName:'',
    })
    that.hideModal()
    that.refreshDevices()
  },
  resetmodule(e) {

  },
  hideModal(e) {
    this.setData({
      scanModal: false,
      logicModal:false,
      logicDeleteModal:false
    })
  },
  showModal() {
    this.setData({
      loadModal: true
    })
  },
  disableModal() {
    setTimeout(
      () => {
        this.setData({
          loadModal: false
        })
      }, 300
    )
  },
  refreshDevices() {

    const that = this;
    const portstr = JSON.stringify();
    const str = JSON.stringify(that.data.userID);
    console.log("input str", str, portstr)
    that.showModal();
    httpPost('https://fdxt.xyz:5050', {
      port: JSON.stringify("offline_module_list"),
      userID: JSON.stringify(that.data.userID)
      //自动获取用户信息嵌套进了自动登录中，以解决js执行顺序不是从上到下的问题
    }, ).then((res) => {
      console.log("offline_module_list :", res)
      if (res.data.list)
        that.setData({
          OfflineModules: res.data.list
        })
    }).catch((res) => {
      console.log(res)
    })
    httpPost('https://fdxt.xyz:5050', {
      port: JSON.stringify("online_list"),
      userID: JSON.stringify(that.data.userID)
      //自动获取用户信息嵌套进了自动登录中，以解决js执行顺序不是从上到下的问题
    }, ).then((res) => {
      console.log("online_list :", res)

    

      that.setData({
        OnlineControlers: res.data.control_list,
        OnlineModules: res.data.module_dict,
      })
    }).catch((res) => {
      console.log(res)
    })
    httpPost('https://fdxt.xyz:5050', {
      port: JSON.stringify("query_logic"),
      userID: JSON.stringify(that.data.userID)
      //自动获取用户信息嵌套进了自动登录中，以解决js执行顺序不是从上到下的问题
    }, ).then((res) => {
      console.log("logiclink", res)
      if (res.data)
      {
        // console.log("保存离线控制中心")
        that.setData({
         logicLink: res.data
        })


      }
    }).catch((res) => {
      console.log(res)
    })
    httpPost('https://fdxt.xyz:5050', {
      port: JSON.stringify("offline_control_list"),
      userID: JSON.stringify(that.data.userID)
      //自动获取用户信息嵌套进了自动登录中，以解决js执行顺序不是从上到下的问题
    }, ).then((res) => {
      console.log("offline_control_list:", res)
      if (res.data.list)
      // wx.setStorage({
      //   key:"OfflineControlers",
      //   value:res.data.list
      // })
      {
        console.log("保存离线控制中心")
        that.setData({
         OfflineControlers: res.data.list
        })

        that.transData()    //数据处理函数
        // that.transData()    //数据处理函数
        that.refreshLogic()
      }
    }).catch((res) => {
      console.log(res)
    })
  

    that.disableModal()

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  transData() {
    const that = this;
    let oflControlerList = that.data.OfflineControlers;
    let oflModuleList = that.data.OfflineModules;
    let olControlerList = that.data.OnlineControlers;
    let olModuleList = that.data.OnlineModules;
    let devices;
    console.log(oflControlerList)
      olControlerList.forEach((ele) => {
        ele['clicked'] = false;
        console.log("###",ele);
      })
    console.log("获取列表：", oflModuleList, oflControlerList, olModuleList, olControlerList)

    var oflDevices = {
      ctrl: oflControlerList,
      Mod: oflModuleList
    }
  
    devices = {
      olDevices: olControlerList,
      oflDevices: oflDevices
    }
    
    console.log(devices)
    that.setData({
   
      ALLOffLine:false,
      'devices': devices,
    })

  },
  cobTypeID(type,id){
      type=id+type<<4;
      // console.log(type)
      return type;
  }, // 组合type与id
  getAllModules()
  {
    const that= this;
    let oflModuleList = that.data.OfflineModules;
    let olModuleList = that.data.OnlineModules;
    let allModuleList=[]
    console.log("onlineModule List",olModuleList)
    for(var ele in olModuleList)
    {
      olModuleList[ele].forEach((mod)=>{ allModuleList=allModuleList.concat(mod)})
     
    }
    allModuleList=allModuleList.concat(oflModuleList)
    return allModuleList
  },
  changePolar()
  {
    this.data.polarLogic=!this.data.polarLogic
  },
  refreshLogic(){
    const that =this;
    // var logicModules=[{id:1,name:"旺财",type:0xF},{id:1,name:"阿威",type:0x1},{id:1,name:"阿曦",type:0x2},{id:1,name:"阿宇",type:0x0}]// 测试用的代码
   var  logicModules=that.getAllModules();

   var link =[];
   var logicLink=that.data.logicLink;
  
   console.log("所以模块为",logicModules)
    var logicTypeIDModules={};   // 测试数据
    var data=[];
    var lock=0;
    var mid=0;
    var sensor=0;
    logicModules.forEach((ele,index,arr)=>{
      if(ele.type==0x0|ele.type==0x7)
        lock++;
      else if(ele.type==0xF)
        mid++;
      else sensor++;
      logicTypeIDModules[ that.cobTypeID(ele.type,ele.id)]=ele;
      if(ele.type!=15)
      data.push({
        name:that.data.moduleDict[ele.type]+ele.name,
        modId:ele.id,
        modType:ele.type,
        x:(ele.type==0x0|ele.type==0x07)?300:(ele.type==0xF?600:900),
        y:ele.type==0x0|ele.type==0x07?(100+lock*200):(ele.type==0xF?(100+mid*200):100+sensor*200),
        itemStyle:ele.type==0x0|ele.type==0x07?{
          color: '#37A2DA'
        }:(ele.type==0xF?{
          color: '#32C5E9'
        }:{
          color: '#32ffE9'
        }),
      })
      that.setData({
        logicTypeIDModules:logicTypeIDModules
      })
      // console.log(logicTypeIDModules)
    })
    console.log(logicLink)
    logicLink.forEach((ele,index,arr)=>{
      var sourceIndex=0;
      var targetIndex=0;
      console.log("logic is ",ele)
      console.log("data is ",data)
      data.forEach((mod,index,arr)=>{
          if(ele.sourceModule.id==mod.modId&&ele.sourceModule.type==mod.modType)
          {sourceIndex=index;console.log(index)}
          if(ele.desModule.id==mod.modId&&ele.desModule.type==mod.modType)
          targetIndex=index;
          // console.log("modis ",mod)
      })
      if(sourceIndex!=targetIndex)
      link.push({source: sourceIndex,
       target: targetIndex,
       lineStyle:ele.logicType==1?{
        width: 5,
        color:'#FB5430',
        curveness: 0.2
    }:{
      width: 5,
      color:'#111111',
      curveness: 0.2
  }})
   })
    if(logicModules.length==0)
         data=[] 
   console.log("logicModules.length",logicModules.length)
   that.setData({
      echartsData:data
    })
    console.log("link is ",link)
    var series =[{
      type: 'graph',
      layout: 'none',
      symbolSize: 50,
      roam: true,
      label: {
        normal: {
          show: true
        }
      },
      edgeSymbol: ['circle', 'arrow'],
      edgeSymbolSize: [4, 10],
      edgeLabel: {
        normal: {
          textStyle: {
            fontSize: 20
          }
        }
      },
      data: data,
      links: link,
     
      lineStyle: {
        normal: {
          opacity: 0.9,
          width: 2,
          curveness: 0.2
        }
      }
    }]
    
    setTimeout(()=>{
      var ct=that.selectComponent("#mychart-one");
      ct.chart.on('click',{dataType: 'node'},that.graphNodeClickHuddle)
      ct.chart.on('click',{dataType: 'edge'},that.graphEdgeClickHuddle)
      ct.chart.setOption({
        series:series
      })
      console.log(ct);
    },500
    )
  },
  graphEdgeClickHuddle(para)
  {
    const that =this 
    that.setData({
      logicDeleteModal:true
    })
    console.log("para is " ,that.data.echartsData)
    that.setData({
      logicToDelete:{
        sourceModule:{
          id:that.data.echartsData[para.data.source].modId
          ,
          type:that.data.echartsData[para.data.source].modType
         },desModule:{
            id:that.data.echartsData[para.data.target].modId
            ,
            type:that.data.echartsData[para.data.target].modType 
         }
      }
    })
  },
  graphNodeClickHuddle(para)
  {
    const that=this;
    const typeid=that.cobTypeID(para.data.modType,para.data.modId);
    if(that.data.hover==false)
    {
      that.setData({
        hover:true,
        sourceModule:{type:para.data.modType,id:para.data.modId}
      })
    }
    else{
      if(that.data.sourceModule.type==para.data.modType&&that.data.sourceModule.id==para.data.modId)
     { 
       wx.showModal({
        title:"无法自我关联！"
      })
      that.setData({
        hover:false,
        sourceModule:{}
      })
    }else 
      
      that.setData({
        logicModal:true,
        desModule:{type:para.data.modType,id:para.data.modId}
      })
    }
    console.log(para)
    // console.log(that.data.hover)
  },
  cancelDeleLogic(){
    const that=this;
    that.setData(
      {
        logicToDelete:{},
      }
    )
    that.hideModal()
    setTimeout(that.refreshDevices,100);
  },
  deleLogic(){
    const that =this ;
    httpPost('https://fdxt.xyz:5050', {
      port: JSON.stringify("delete_logic"),
      userID: JSON.stringify(that.data.userID),
      sourceModule:JSON.stringify(that.data.logicToDelete.sourceModule),
      desModule:JSON.stringify(that.data.logicToDelete.desModule),
    }, ).then((res) => {
      console.log("接受数据 :", res)
    }).catch((res) => {
      console.log(res)
    })
    that.cancelDeleLogic();
  },
  subLogic(){
    const that=this;
    let logicType="1";
    if(!that.data.polarLogic)
      logicType="0";
    httpPost('https://fdxt.xyz:5050', {
      port: JSON.stringify("add_logic"),
      userID: JSON.stringify(that.data.userID),
      sourceModule:JSON.stringify(that.data.sourceModule),
      desModule:JSON.stringify(that.data.desModule),
      logicType:logicType
    }, ).then((res) => {
      console.log("接受数据 :", res)
    }).catch((res) => {
      console.log(res)
    })
    that.cancelSubLogic();

  },
  cancelSubLogic(){
    const that=this;
    that.setData(
      {
        sourceModule:{},
        desModule:{},
        hover:false,
        polarLogic:true
      }
    )

    that.hideModal()
    setTimeout(that.refreshDevices,100);
  },
  cancelSubModule()
  {
    this.setData(
      {
        ModalName:''
      }
    )
    this.hideModal()

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  configMod(e)
  {
    const that = this ;
    console.log(e)
    that.setData(
      {
        currentType:e.currentTarget.dataset.currenttype,
        currentID:e.currentTarget.dataset.currentid,
        configModal:true
      }
    )
  },
  hideConfigMod(e)
  {
    const that = this ;
    that.setData(
      {
        configModal:false
      }
    )
    setTimeout(()=>{that.setData({        currentType:null, currentID:null})},500)
  },
  ScanConfig(e){
console.log(e)
const that=this;
    if(e.detail.value.maxtrial!="")
    httpPost('https://fdxt.xyz:5050', {
      port: JSON.stringify("set_module_extra_num"),
      userID: JSON.stringify(that.data.userID),
     id:JSON.stringify(that.data.currentID),
     type:JSON.stringify(that.data.currentType),
     extra_num:JSON.stringify(e.detail.value.maxtrial),
    }, ).then((res) => {
      console.log("接受数据 :", res)
    }).catch((res) => {
      console.log(res)
    })

    that.hideConfigMod()
  }
,

  deleteControler: function (id) {
    const that = this
    wx.showModal({
      title: '确认要删除锁体吗',
      content: '删除锁体后将无法恢复',
      success: function (res) {
        if (res.confirm) //用户点击确认后才进行操作
        {
          wx.request({ //获取是否注册、用户名、手机号、智能逻辑
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'chartset': 'utf-8'
            },
            url: 'https://fdxt.xyz:5050', //服务器API的url
            data: {
              port: JSON.stringify("delete_control"),
              controlID: JSON.stringify(id),
            },
            success: function (res) { //wx.request 成功
              console.log("删除锁体成功，res：", res)
              if (res.data.state == "1") //
              {
                wx.showToast({
                  title: '删除成功！',
                  icon: 'success',
                  duration: 2000
                })
               that.refreshDevices()
              } else {
                console.log("更新设置失败但在success中")
                wx.showToast({
                  title: '失败请重试',
                  icon: 'none'
                })
              }
            },
            fail: function (res) { //wx.request 失败
              console.log("更新设置失败，res：", res)
              wx.showToast({
                title: '失败请重试',
                icon: 'none'
              })
            },
          })

        }
      }
    })

  },
  deleteOflControler: function (e) {
    this.deleteControler(e.currentTarget.dataset.id);
  },
  deleteOflModule: function (e) {
    var that = this;
    const id= e.currentTarget.dataset.id;
    const type= e.currentTarget.dataset.type;
    console.log("id,type:",id,type)
    wx.showModal({
      title: '确认要删除锁体吗',
      content: '删除锁体后将无法恢复',
      success: function (res) {
        if (res.confirm) //用户点击确认后才进行操作
        {
          wx.request({ //获取是否注册、用户名、手机号、智能逻辑
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'chartset': 'utf-8'
            },
            url: 'https://fdxt.xyz:5050', //服务器API的url
            data: {
              port: JSON.stringify("delete_module"),
              moduleID: JSON.stringify(id),
              moduleType: JSON.stringify(type)
            },
            success: function (res) { //wx.request 成功
              console.log("删除锁体成功，res：", res)
              if (res.data.state == "1") //
              {
                wx.showToast({
                  title: '删除成功！',
                  icon: 'success',
                  duration: 2000
                })
                that.refreshDevices()
              } else {
                console.log("更新设置失败但在success中")
                wx.showToast({
                  title: '失败请重试',
                  icon: 'none'
                })
              }
            },
            fail: function (res) { //wx.request 失败
              console.log("更新设置失败，res：", res)
              wx.showToast({
                title: '失败请重试',
                icon: 'none'
              })
            },
          })

        }
      }
    })
  },

 
  shoot: function (x) {
    const that = this
    wx.request({
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'chartset': 'utf-8'
      },
      url: 'https://fdxt.xyz:5050', //服务器API的url
      data: {
        port: JSON.stringify("photo"),
        lockID: JSON.stringify(11111),
        userID: JSON.stringify(that.data.userID),
      },
      success: function (res) { //wx.request 成功
        console.log("拍照成功，res：", res)
        if (res.data.state == "1") //服务器端拍照成功
        {
          wx.showToast({
            title: '拍摄成功！',
            icon: 'success',
            duration: 2000
          })
          that.setData(
            {
              imgShow:true,
              imgUrl:res.data.url
            }
            )
        } else {
          console.log("服务器端拍摄失败")
          wx.showToast({
            title: '失败请重试',
            icon: 'none',
            duration: 2000

          })
        }
      },
      fail: function (res) { //wx.request 失败
        console.log("拍摄request失败，res：", res)
        wx.showToast({
          title: '失败请重试',
          icon: 'none',
          duration: 2000
        })
      },
    })


  },
  ed0: function () {
    this.setData({
      image0: 1
    })
  },
  ed1: function () {
    this.setData({
      image1: 1
    })
  },
  ed2: function () {
    this.setData({
      image2: 1
    })
  },


  download: function () {
    const that = this;
if(that.data.imgShow)
{
    wx.downloadFile({
      url: that.data.imgUrl,
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        console.log("下载成功", res);
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function () {
              wx.showToast({
                title: '保存成功！',
                icon: 'success',
                duration: 2000
              })
            },
            fail: function (err) {
              console.log("保存相册失败,err:", err);
              if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                console.log("用户一开始拒绝了，我们想再次发起授权")
                alert('打开设置窗口')
                wx.openSetting({
                  success(settingdata) {
                    console.log(settingdata)
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                    } else {
                      console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                    }
                  }
                })
              }

            }
          })
        }
      },
      fail: function (res) {
        console.log(res)
      }
    })
  }else 
  {
    wx.showModal({
      title:"暂无拍摄图片"
    })
  }
},

  download0: function () {
    this.download(0)
  },

  download1: function () {
    this.download(1)
  },

  download2: function () {
    this.download(2)
  },

  //人脸识别
  //======================这个写的比较完善，可以借鉴这个===============
  face: function () {
    const that = this
    var moduleType=that.data.currentType
    var moduleId=that.data.currentID
    let olModuleList = that.data.OnlineModules;
    let controlerID;
    for ( var key in olModuleList)
    {
      if(olModuleList[key].id==moduleId&&olModuleList[key].type==moduleType)
     { controlerID=key;
      break;
    }
    }
    // var lockx = that.data.lock_list[x].lockName //用于显示锁体名称
    var locktxt = "识别成功"
    locktxt =locktxt
    wx.request({
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'chartset': 'utf-8'
      },
      url: 'https://fdxt.xyz:5050', //服务器API的url
      data: {
        port: JSON.stringify("face"),
        lockID: JSON.stringify(controlerID),
        userID: JSON.stringify(that.data.userID),
      },
      /*
       *这时已经请求了服务器，需要给用户进行提示
       *这里无条件提示3秒
       */
      success: function (res) { //wx.request 成功
        console.log("人脸识别传送至服务器成功，res：", res)
        wx.showToast({
          title: '正在进行人脸识别...',
          icon: 'loading',
          duration: '3000', //等待3秒
          mask: 1
        })
        if (res.data.state == "1") //服务器端拍照成功
        {
          wx.showToast({
            title: locktxt, //=======注意此处最多显示7个汉字
            icon: 'success',
            duration: 2000
          })
        } else if (res.data.state == "0") {
          console.log("人脸识别失败")
          wx.showToast({
            title: '人脸识别失败',
            icon: 'error',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '服务器请求失败',
            icon: 'error',
            duration: 2000
          })
        }
      },
      fail: function (res) { //wx.request 失败
        console.log("人脸识别request失败，res：", res)
        wx.showToast({
          title: '服务器请求失败',
          icon: 'error',
          duration: 2000
        })
      },
    })


  },

  //通过摄像头模块获取人脸特征============
  //先拍照
  getface: function (x) {
    const that = this
    var lockx = that.data.lock_list[x].lockName //用于显示锁体名称
    var locktxt = "存储成功"
    locktxt = lockx + locktxt
    var lockfail = "特征提取失败"
    wx.request({
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'chartset': 'utf-8'
      },
      url: 'https://fdxt.xyz:5050', //服务器API的url
      data: {
        port: JSON.stringify("getface"),
        lockID: JSON.stringify(that.data.lock_list[x].lockID),
        userID: JSON.stringify(that.data.userID),
      },
      success: function (res) { //wx.request 成功
        console.log("人脸特征上传成功，res：", res)
        wx.showToast({
          title: '正在进行特征提取...',
          icon: 'loading',
          duration: '3000', //等待3秒
          mask: 1
        })
        if (res.data.state == "2") //其他错误
        {
          console.log("服务器返回其他错误，res：", res)
          wx.showToast({
            title: '发生错误',
            icon: 'errpr',
            duration: '1000', //等待1秒
            mask: 0
          })
        } else if (res.data.state == "1") //服务器端拍照成功
        {
          if (x == 0) {
            that.setData({
              "facephoto[0]": res.data.url,
            })
          } else if (x == 1) {
            that.setData({
              "facephoto[1]": res.data.url,
            })
          } else if (x == 2) {
            that.setData({
              "facephoto[2]": res.data.url,
            })
          }
          wx.showToast({
            title: '特征储存成功！',
            icon: 'success',
            duration: 2000
          })
        } else { //服务器返回“0”
          console.log("服务器端识别失败")
          wx.showToast({
            title: '特征提取失败，请对准摄像头重试',
            icon: 'none',
            duration: 2000

          })
        }
      },
      fail: function (res) { //wx.request 失败
        console.log("拍摄request失败，res：", res)
        wx.showToast({
          title: '失败请重试',
          icon: 'none',
          duration: 1000
        })
      },
    })


  },

  getface0: function () {
    this.getface(0)
  },

  getface1: function () {
    this.getface(1)
  },

  getface2: function () {
    this.getface(2)
  },

})